<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Keycloak Single-Page Application Example</title>
    <script type="importmap">
      {
        "imports": {
          "keycloak-js": "/vendor/keycloak.js"
        }
      }
    </script>
    <link rel="modulepreload" href="/vendor/keycloak.js">
  </head>
  <body>
    <div id="user" style="display: none;">
      <button id="logout" type="button">Logout</button>
      <button id="showMyAccount" type="button">My Account</button>
      <button id="showIdToken" type="button">Show ID Token</button>
      <button id="showAccessToken" type="button">Show Access Token</button>
      <button id="refreshToken" type="button">Refresh</button>
      <hr>
      <h2 id="name"></h2>
      <pre id="output"></pre>
    </div>
    <script type="module">
      import Keycloak from "keycloak-js";

      const outputElement = document.getElementById("output");
      const nameElement = document.getElementById("name");
      const userElement = document.getElementById("user");

      function output(content) {
        if (typeof content === "object") {
          content = JSON.stringify(content, null, 2);
        }

        outputElement.textContent = content;
      }

      function showProfile() {
        const name =
          keycloak.idTokenParsed.name ||
          keycloak.idTokenParsed.preferred_username;

        nameElement.textContent = `Hello ${name}`;
        userElement.style.display = "block";
      }

      document.getElementById("logout").addEventListener("click", () => {
        keycloak.logout();
      });

      document.getElementById("showIdToken").addEventListener("click", () => {
        output(keycloak.idTokenParsed);
      });

      document
        .getElementById("showAccessToken")
        .addEventListener("click", () => {
          output(keycloak.tokenParsed);
        });

      document
        .getElementById("refreshToken")
        .addEventListener("click", async () => {
          await keycloak.updateToken(-1);
          output(keycloak.idTokenParsed);
          showProfile();
        });

      document
        .getElementById("showMyAccount")
        .addEventListener("click", async () => {
          await keycloak.accountManagement()
        });

      const keycloak = new Keycloak({
        url: "http://localhost:8180",
        realm: "quickstart",
        clientId: "spa",
      });

      await keycloak.init({ onLoad: "login-required" });
      showProfile();
    </script>
  </body>
</html>